package com.myhome.controller;

import com.myhome.config.constant.R;
import com.myhome.geetest.GeetestLib;
import com.myhome.geetest.GeetestLibResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springside.modules.utils.net.IPUtil;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author QYiXin
 * @Date 2021 10 14 13 27
 **/
@RestController
@Api(tags = "极域验证的数据接口")
@RequestMapping("/gt")
public class GeeTestController {
    @Autowired
    GeetestLib geetestLib;
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/register")
    @ApiOperation("获取第一次数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "用户的唯一标识")
    })
    public R<String> register(String uuid) throws Exception {
        System.out.println("uuid:  "+uuid);//9ca323c2-a63c-4b0e-adba-5a22ae921b13
        String digestmod = "md5";
        // 构造极验数据包
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("digestmod", digestmod);
        paramMap.put("user_id", uuid);
        paramMap.put("client_type", "web");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        paramMap.put("ip_address", InetAddress.getLocalHost().getHostAddress());

        GeetestLibResult result = geetestLib.register(digestmod, paramMap);
        // 将结果状态写到session中，此处register接口存入session，后续validate接口会取出使用
        // 注意，此demo应用的session是单机模式，格外注意分布式环境下session的应用
        redisTemplate.opsForValue().set(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY + ":" + uuid, result.getStatus(),180, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(GeetestLib.GEETEST_SERVER_USER_KEY+ ":" + uuid, uuid);
        // 注意，不要更改返回的结构和值类型
        return R.ok(result.getData());
    }
}

